package com.tnsw.noxnox.settopbox;

import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.http.THttpBase;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class STBService extends IntentService {

	private static boolean sIsRunning = false;
	private static STBService sInstance;
	private AsyncManager asyncManager;
	private String tag = "STBService";
	
	private STBWebserver webserver;
	private STBTVScreen tv;
	
	public STBService() {
		super("");
		Log.d(tag, "Constructor()");
		this.asyncManager = AsyncManager.getInstance();
		
		sInstance = this;
		sIsRunning = true;
	}
	
	public STBService(String name) {
		super(name);
		Log.d(tag, "Constructor(" + name + ")");
		this.asyncManager = AsyncManager.getInstance();
		
		sInstance = this;
		sIsRunning = true;
	}
	
	public static STBService getInstance() {
		//if (sIsRunning == false) {
		//	sInstance = new STBService();
		//}
		
		return(sInstance);
	}
	

	@Override
	protected void onHandleIntent(Intent intent) {
		
	}

	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(tag, "onStartCommand(flags=" + flags + ", startId=" + startId + ")");
		this.asyncManager.appendNetworkLog("STBService started");
		
		try {
			this.webserver = new STBWebserver(this, 7778);
			this.webserver.getHttpRegistry().register("/stb/*", new STBWebHandler(this));
			this.webserver.startThread();
			
			String wifiIP = THttpBase.getWiFiIPAddress(this);
			this.asyncManager.appendNetworkLog("Listening at WIFI IP:" + wifiIP);
		} catch (Exception e) {
			Log.e(tag, "onStartCommand - " + e.toString(), e);
			this.asyncManager.appendNetworkLog("onStartCommand - " + e.toString());
		}
		
		
		return(START_STICKY);
	}
	
	public void registerTVScreen(STBTVScreen tv) {
		this.tv = tv;
	}
	
	public void playUrl(String url) {
		if (this.tv != null) {
			this.tv.doPlay(url);
		} else {
			Log.e(tag, "Cannot plau url=" + url + " because there is no STBTVScreen object registered");
		}
	}

}
